package com.lang.controller;

import com.google.gson.Gson;
import com.lang.entity.User;
import com.lang.service.UserService;
import com.lang.service.impl.UserServiceImpl;
import com.lang.utils.StrUtils;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/*
 * @Date : 2024/3/15 13:45
 * @Created by Lang
 * @ProjectName : LclShop
 */
@WebServlet("/admin/user")
public class AdminServlet extends BaseServlet {
    private UserService userService = new UserServiceImpl();

    public String login(HttpServletRequest request, HttpServletResponse response) {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        User user = userService.adminLogin(username, password);
        if (user == null) {
            request.setAttribute("msg", "该用户不是管理员");
            return StrUtils.FORWARD + "/admin/login.jsp";
        }
        request.setAttribute("admin", user);
        request.getSession().setAttribute("admin", user);

        return StrUtils.FORWARD + "/admin/admin.jsp";
    }

    public String showUser(HttpServletRequest request, HttpServletResponse response) {
        List<User> list = userService.list();
        return new Gson().toJson(list);
    }

    public String searchUser(HttpServletRequest request, HttpServletResponse response) {
        String username = request.getParameter("username");
        String gender = request.getParameter("gender");

        List<User> search = userService.search(username, gender);
        return new Gson().toJson(search);
    }

    public String deleteUser(HttpServletRequest request, HttpServletResponse response) {
        String id = request.getParameter("id");
        int res = userService.deleteUser(id);
        return "ok";
    }
}
